import random

from models.Food import Food
from models.Organism import Organism


class World:
    def __init__(self, width, height, num_foods, num_organisms):
        self.width = width
        self.height = height
        self.foods = [Food((random.randint(0, width-1), random.randint(0, height-1))) for _ in range(num_foods)]
        self.organisms = [Organism((random.randint(0, width-1), random.randint(0, height-1))) for _ in range(num_organisms)]
        self.current_generation = 0
        self.generations_alive = 0  # 种群存活代数

    def update(self):
        self.current_generation += 1
        self.generations_alive = self.current_generation  # 更新存活代数
        self.organisms = [o for o in self.organisms if o.alive]
        for organism in self.organisms:
            organism.move(self)
            organism.eat(self)
            organism.reproduce(self)
        self._generate_food()

    def add_food(self, num_foods):
        self.foods += [Food((random.randint(0, self.width-1), random.randint(0, self.height-1))) for _ in range(num_foods)]

    def _generate_food(self):
        # 动态调整食物生成量（根据种群数量）
        num_new_foods = max(2, int(len(self.organisms) * 0.1))  # 每10个生物生成2个新食物
        for _ in range(num_new_foods):
            self.foods.append(Food((random.randint(0, self.width-1), random.randint(0, self.height-1))))
